// pages/login/login.js
var util = require("../../utils/util.js")
var api = require("../../utils/api.js")
console.log(api)
var app = getApp();
var interval = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    Type: 1,
    username: '',
    userpasd: '',
    authcode: '',
    time: '获取验证码', //倒计时 
    currentTime: 60, //限制60s
    isClick: '', //获取验证码按钮，默认允许点击
    codeArr: [],
    nickName: '',
    avatarUrl: '',
    account: 1,
    dis: false
  },
  lgmoblie: function () {
    var that = this
    that.setData({
      Type: 1,
      account: 1,
    })
  },
  login: function () {
    var that = this
    that.setData({
      Type: 2,
      account: 2,
    })
  },
  registered: function () {
    var that = this
    that.setData({
      Type: 3
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */

  //获取账号赋给username
  usernameInput: function (event) {
    this.setData({
      username: event.detail.value
    })
  },
  //获取密码赋给pass
  userpswdInput: function (event) {
    this.setData({
      userpasd: event.detail.value
    })
  },
  //获取验证码
  authcodeInput: function (event) {
    this.setData({
      authcode: event.detail.value
    })
  },
  butt: function () {
    let that = this;
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/; // 判断手机号码的正则
    if (that.data.username.length == 0) {
      api.showError('账号不能为空')
      return;
    }
    if (that.data.username.length < 11) {
      api.showError('账号长度有误！')
      return;
    }
    if (that.data.userpasd.length < 6) {
      api.showError('密码不能小于六位数')
      return;
    }
    var data = {
      mobile: that.data.username,
      pass: that.data.userpasd
    }
    var url = app.u.HOME_URL + app.u.LOGIN

    api.requestUrl(data, url).then(res => {
      if (res.code == 200) {
        wx.setStorage({
          key: 'userInfo',
          data: res.data,
        })
        api.showError("登录成功")
        setTimeout(function () {
          wx.navigateBack({
            //delta: 1, // 回退前 delta(默认为1) 页面
            success: function (res) {
              // success
              wx.setStorage({
                key: 'userInfo',
                data: res.data,
              })
            },
            fail: function () {
              wx.switchTab({
                url: '/pages/index/index'
              })
            }
          })
        }, 800)
      } else {
        api.showError(res.msg)
      }

    })
  },
  //一键登录
  tologin: function () {
    var that = this;
    wx.login({
      success: function (res) {
        var url = app.u.HOME_URL + app.u.GETOPENID
        var data = {
          code: res.code,
        }
        //从后台拿到openid，存到缓存里面
        api.requestUrl(data, url).then(res => {
          wx.setStorage({
            key: 'openId',
            data: res.data.openid,
          })
          var url2 = app.u.HOME_URL + app.u.OPENID_LOGIN
          var data2 = {
            openid: res.data.openid,
          }
          //将用户信息存到缓存
          api.requestUrl(data2, url2).then(res => {
            if (res.code == 200) {
              wx.setStorage({
                key: 'userInfo',
                data: res.data,
              })
              api.showSuccess(res.msg)
              setTimeout(function () {
                wx.navigateBack({
                  delta: 1, // 回退前 delta(默认为1) 页面
                  success: function (res) {
                    // success
                  },
                  fail: function () {
                    wx.switchTab({
                      url: '/pages/index/index'
                    })
                  }
                })
              }, 800)
            } else {
              api.showError(res.msg)
            }

          })
        })

      }
    })
  },
  onLoad: function (options) {
    var that = this
    that.setData({
      Type: 1
    })
    wx.getUserInfo({
      success: function (res) {
        var userInfo = res.userInfo
        that.setData({
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl
        })
      },
      fail: function () {
        wx.navigateTo({
          url: '../sq/sq'
        })
      }
    })

  },
  countDown: function () {
    let that = this;
    /*第一步：验证手机号码*/
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/; // 判断手机号码的正则
    if (that.data.username.length == 0) {
      api.showError('手机号码不能为空')
      return;
    }

    if (that.data.username.length < 11) {
      api.showError('手机号码长度有误！')
      return;
    }

    if (!myreg.test(that.data.username)) {
      api.showError('错误的手机号码！')
      return;
    }
    /*第二步：设置计时器*/
    // 先禁止获取验证码按钮的点击
    that.setData({
      isClick: 'other',
      dis: true
    })
    // 60s倒计时 setInterval功能用于循环，常常用于播放动画，或者时间显示
    var currentTime = that.data.currentTime;
    interval = setInterval(function () {
      currentTime--; //减
      that.setData({
        time: currentTime + '秒后获取'
      })
      if (currentTime <= 0) {
        clearInterval(interval)
        that.setData({
          time: '获取验证码',
          currentTime: 60,
          isClick: '',
          dis: false
        })
      }
    }, 1000);
    /*第三步：请求验证码接口，并记录服务器返回的验证码用于判断，这里服务器也可能不返回验证码，那验证码的判断交给后台*/

    wx.request({
      url: app.u.HOME_URL + app.u.SENDMESSAGE, //请求接口的url
      method: 'GET', //请求方式
      data: {
        mobile: that.data.username
      }, //请求参数
      header: {
        'content-type': 'application/json' // 默认值
      },
      complete() { //请求结束后隐藏 loading 提示框
        wx.hideLoading();
      },
      success: res => {
        that.setData({
          codeArr: res.data.res,
        })
      }
    });
  },

  zhuche: function () {
    let that = this;
    /*第一步：验证手机号码*/
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/; // 判断手机号码的正则
    if (that.data.username.length == 0) {
      api.showError('手机号码不能为空')
      return;
    }

    if (that.data.username.length < 11) {
      api.showError('手机号码长度有误！')
      return;
    }

    if (!myreg.test(that.data.username)) {
      api.showError('错误的手机号码！')
      return;
    }
    if (that.data.authcode.length == 0) {
      api.showError('验证码不能为空')
      return;
    }
    let openid = wx.getStorageSync("openId")
    var info = {
      mobile: that.data.username,
      nick_name: that.data.nickName,
      avatarUrl: that.data.avatarUrl,
      openid: openid
    }
    if (that.data.authcode != that.data.codeArr.code) {
      api.showError('验证码错误')
      return;
    } else {
      var url = app.u.HOME_URL + app.u.REG
      api.requestUrl(info, url).then(res => {
        if (res.code == 200) {
          wx.setStorage({
            key: "userInfo",
            data: res.data
          })
          api.showError(res.msg)

          setTimeout(function () {
            wx.switchTab({
              url: '../index/index',
            });
          }, 1000);
        } else {
          api.showError(res.msg)
        }
      })
    }
  },
  dologin: function () {
    let that = this;
    /*第一步：验证手机号码*/
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/; // 判断手机号码的正则
    if (that.data.username.length == 0) {
      api.showError('手机号码不能为空')
      return;
    }

    if (that.data.username.length < 11) {
      api.showError('手机号码长度有误！')
      return;
    }

    if (!myreg.test(that.data.username)) {
      api.showError('错误的手机号码！')
      return;
    }
    if (that.data.authcode.length == 0) {
      api.showError('验证码不能为空')
      return;
    }
    var info = {
      mobile: that.data.username
    }
    if (that.data.authcode != that.data.codeArr.code) {
      api.showError('验证码错误')
      return;
    } else {
      var url = app.u.HOME_URL + app.u.CODELOGIN
      api.requestUrl(info, url).then(res => {
        if (res.code == 200) {
          wx.setStorage({
            key: 'userInfo',
            data: res.data,
          })
          setTimeout(function () {
            wx.switchTab({
              url: '../index/index',
            });
          }, 1500);
        }


      })
    }
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    wx.showShareMenu({
      withShareTicket: true
    })
  },
})